﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.ComponentModel;

namespace WebSite.CustomControl
{
    /// <summary>
    /// WelcomeLabel is a custom control which cames from label
    /// </summary>
    [
        AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal),
        AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal),
        DefaultProperty("Text"),
        ToolboxData("<{0}:WelcomeLabel runat=\"server\"> </{0}:WelcomeLabel>")
    ]
    public class WelcomeLabel : Label
    {
        public WelcomeLabel()
        {

        }

        [
            Bindable(false),
            Category("Appearance"),
            Description("The text to use if the user is not authenticated."),
            DefaultValue("Guest"),
            Localizable(true)
        ]
        public string NameForAnonymousUser
        {
            get
            {
                string s = (string)ViewState["NameForAnonymousUser"];
                return (s == null) ? String.Empty : s;
            }
            set
            {
                ViewState["NameForAnonymousUser"] = value;
            }
        }
        protected override void RenderContents(HtmlTextWriter writer)
        {
            writer.WriteEncodedText(Text);
            if (Context != null)
            {
                string s = Context.User.Identity.Name;
                if (s != null && s != String.Empty)
                {
                    string[] split = s.Split('\\');
                    int n = split.Length - 1;
                    if (split[n] != String.Empty)
                    {
                        writer.Write(", ");
                        writer.Write(split[n]);
                    }
                }
                else
                {
                    if (NameForAnonymousUser != String.Empty)
                    {
                        writer.Write(", ");
                        writer.Write(NameForAnonymousUser);
                    }
                    else
                    {
                        writer.Write("!");
                    }
                }
            }
        }
    }
}
